import time
import traceback
import os
import json

from PyQt6.QtCore import QThread, pyqtSignal
from PyQt6.QtWidgets import QWidget, QDialog, QVBoxLayout, QProgressBar, QMessageBox
from uidemo.comare import Ui_compare
from common.doexcel import do_txt
from common.initpath import localdatapath, sourcepath, init_excel_dir
from common.dosvn import diff_by_url, diff_by_version


class CompareImpl(QWidget, Ui_compare):
    def __init__(self):
        super().__init__()
        self.setupUi(self)  # 初始化界面
        self.progress_dialog = None  # 进度条功能
        self.local_data = {}  # 缓存数据处理
        # 处理本地缓存初始状态
        if os.path.exists(localdatapath):
            init_excel_dir()
            self.init_data()
        else:
            self.save_all_input()

        # 绑定按钮事件
        self.do_version.clicked.connect(lambda: self.show_progress_dialog(self.by_version))
        self.do_url.clicked.connect(lambda: self.show_progress_dialog(self.by_url))
        self.do_local.clicked.connect(lambda: self.show_progress_dialog(self.by_local))
        self.do_savecompare.clicked.connect(self.save_all_input)

    def init_data(self):
        with open(localdatapath, 'r', encoding='utf-8') as f:
            self.local_data = json.load(f)
        self.line_version_url.setText(self.local_data['line_version_url'])
        self.line_version.setText(self.local_data['line_version'])
        self.line_version_2.setText(self.local_data['line_version2'])
        self.line_old_url.setText(self.local_data['line_old_url'])
        self.line_new_url.setText(self.local_data['line_new_url'])
        self.comparepath.setText(self.local_data['comparepath'])

    def show_progress_dialog(self, func):
        """显示进度条对话框并启动任务"""
        self.progress_dialog = ProgressDialog(func)
        self.progress_dialog.worker.start()  # 启动子线程
        self.progress_dialog.exec()  # 显示对话框（模态）

    # 版本对比
    def by_version(self):
        svn_url = self.line_version_url.text()
        old_v = self.line_version.text()
        new_v = self.line_version_2.text()
        if svn_url is '' or old_v is '' or new_v is '':
            return False
        elif self.comparepath.text() is '':
            return False
        else:
            flag = diff_by_version(svn_url, old_v, new_v)
            time.sleep(2)
            if flag:
                do_txt(self.comparepath.text())
        return True

    # url对比
    def by_url(self):
        old_url = self.line_old_url.text()
        new_url = self.line_new_url.text()
        if old_url is '' or new_url is '':
            return False
        elif self.comparepath.text() is '':
            return False
        else:
            flag = diff_by_url(old_url, new_url)
            time.sleep(2)
            if flag:
                do_txt(self.comparepath.text())
        return True

    # 本地对比
    def by_local(self):
        if self.comparepath.text() is '':
            return False
        do_txt(self.comparepath.text())
        return True

    # 缓存所有输入
    def save_all_input(self):
        if not os.path.exists(sourcepath):
            os.mkdir(sourcepath)
        self.local_data['line_version_url'] = self.line_version_url.text()
        self.local_data['line_version'] = self.line_version.text()
        self.local_data['line_version2'] = self.line_version_2.text()
        self.local_data['line_old_url'] = self.line_old_url.text()
        self.local_data['line_new_url'] = self.line_new_url.text()
        self.local_data['comparepath'] = self.comparepath.text()
        with open(localdatapath, 'w', encoding='utf-8') as f:
            json.dump(self.local_data, f, ensure_ascii=False, indent=4)


class Worker(QThread):
    """子线程，用于执行耗时任务"""
    progress_updated = pyqtSignal(int)  # 进度更新信号
    finished = pyqtSignal(str)  # 任务完成信号
    error_occurred = pyqtSignal(str)  # 错误信号，传递错误信息

    def __init__(self, func):
        super().__init__()
        self.func = func

    def run(self):
        """线程执行的任务"""
        try:
            flag = self.func()
            if flag:
                self.finished.emit('done')
            elif flag is False:
                self.error_occurred.emit("请检查输入内容是否为空！")
        except Exception as e:
            # 捕获异常并发送错误信号
            error_msg = traceback.format_exc()  # 获取完整的错误信息
            self.error_occurred.emit(error_msg)


class ProgressDialog(QDialog):
    """置顶的进度条对话框"""

    def __init__(self, func):
        super().__init__()
        self.setWindowTitle("正在处理中,请稍等......")
        self.setGeometry(800, 500, 300, 100)
        # self.setWindowFlags(self.windowFlags() & ~Qt.WindowType.WindowCloseButtonHint)  # 设置关闭按钮无法使用

        # 创建布局和组件
        layout = QVBoxLayout()
        self.progress_bar = QProgressBar(self)
        self.progress_bar.setRange(0, 0)
        layout.addWidget(self.progress_bar)
        self.setLayout(layout)

        # 初始化子线程
        self.worker = Worker(func)
        # self.worker.progress_updated.connect(self.update_progress)
        self.worker.finished.connect(self.task_completed)
        self.worker.error_occurred.connect(self.task_error)

    def update_progress(self, value):
        """更新进度条"""
        self.progress_bar.setValue(value)

    def task_completed(self, msg: str):
        """任务完成"""
        self.close()  # 关闭对话框

    def task_error(self, error_msg):
        # 显示错误信息
        QMessageBox.critical(self, "错误", f"任务出错：\n{error_msg}")
        self.close()
